<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-12-20 14:35:28
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-09-01 15:12:33
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\Edit.vue
 * Copyright (c) 2023 by 李天惊 uf_lee@163.com, All Rights Reserved. 
-->
<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, ref, watch } from 'vue'
import { required } from '@/utils/formRules'
import FoodRefer from './FoodRefer.vue'
import { ElButton, ElInput, ElTabs, ElTabPane, ElMessage } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { Table } from '@/components/Table'
import { spForageListApi } from '@/api/sp/food'
import { useIcon } from '@/hooks/web/useIcon'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const iconDel = useIcon({ icon: 'ep:delete' })
const tabValue: any = ref('1')
const userInfo: any = wsCache.get('userInfo')

import { spForageFormulaSeeApi } from '@/api/sp/food'

import { zcPastureListApi } from '@/api/fa/pasture'
import { ucDeptListApi } from '@/api/uc/dept'
import { ucOrgDeptUserListApi } from '@/api/fa/user'

const myDeptList: any = wsCache.get('myDeptList')
const myUserList: any = ref(wsCache.get('myUserList'))

const newDeptTreeData = ref<any[]>([])
const newUserData = ref<any[]>([])
const data = ref<any>({})
const props = defineProps({
  id: {
    type: String,
    default: null
  }
})

const spForageList = (val) => {
  val.pasture_org_id = data.value.pasture_org_id
  return spForageListApi(val)
}
// 调用查看接口获取信息
const getForageFormulaSee = async () => {
  if (props.id) {
    const res = await spForageFormulaSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = res.data
      await methods.setValues(data.value)
      d_id.value = data.value?.detailed.length
      let aaa = data.value?.detailed
      aaa.forEach((element, index) => {
        element.d_id = index + 1
      })
      data.value.detailed = aaa
      await DeptList(data.value.pasture_org_id)
      if (data.value.pasture_dept_id) {
        await UserList(data.value.pasture_dept_id)
      }

      if (data.value.admin_dept_id) {
        const params = {
          org_id: wsCache.get('userInfo').default_org_id,
          dept_id: data.value.admin_dept_id
        }
        const res = await ucOrgDeptUserListApi(params)
          .catch(() => {})
          .finally(() => {})
        if (res) {
          myUserList.value = res.data
        }
      }
    }
  } else {
    data.value = {
      detailed: []
    }
    await methods.setValues(data.value)
  }
}

// 管理员用户列表
const myUserListChange = async (value) => {
  myUserList.value = []
  data.value.admin_dept_id = value
  data.value.admin_user_id = ''
  data.value.admin_user_name = ''
  const params = {
    org_id: userInfo.default_org_id,
    dept_id: value
  }
  const res = await ucOrgDeptUserListApi(params)
    .catch(() => {})
    .finally(() => {})
  if (res) {
    myUserList.value = res.data
  }
}
const DeptList = async (value) => {
  const res = await ucDeptListApi({ org_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newDeptTreeData.value = res.data
  }
}
const stateChangeAdminUser = async (value) => {
  data.value.admin_user_id = value
}
const stateChangeUser = async (value) => {
  data.value.pasture_user_id = value
}
const UserList = async (value) => {
  data.value.pasture_dept_id = value
  await methods.setValues(data.value)
  newUserData.value = []
  const params = {
    org_id: data.value.pasture_org_id,
    dept_id: data.value.pasture_dept_id
  }
  const res = await ucOrgDeptUserListApi(params)
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newUserData.value = res.data
  }
}

const onChangeWeight = async (value) => {
  data.value.totalWeight = value
  if (tabValue.value == '1') {
    data.value.detailed.forEach((element) => {
      element.weight = (element.ratio * 0.01 * data.value.totalWeight).toFixed(2)
    })
  }
  await methods.setValues(data.value)
}

const onCustomer = async (value) => {
  if (value != data.value.pasture_org_id) {
    data.value.pasture_org_id = value
    newDeptTreeData.value = []
    data.value.pasture_dept_id = ''
    data.value.pasture_dept_name = ''
    data.value.pasture_user_id = ''
    data.value.pasture_user_name = ''
    await DeptList(value)
  }
  await methods.setValues(data.value)
}
const belong_type = reactive([
  { id: 1, label: '比例填写', value: '1' },
  { id: 2, label: '重量填写', value: '2' }
])
const tableDatas: any = reactive([])

const schemaAdd = reactive<FormSchema[]>([
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '所属用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'name',
    component: 'Input',
    label: '配方名称'
  },
  {
    field: 'threshold',
    component: 'Input',
    componentProps: {
      placeholder: '例：1.2'
    },
    label: '默认阀值'
  },
  {
    field: 'totalWeight',
    component: 'Input',
    componentProps: {
      placeholder: '输入公斤数',
      onChange: onChangeWeight
    },
    label: '饲料重量'
  },
  {
    field: 'note',
    component: 'Input',
    label: '备注'
  }
])
const schemaEdit = reactive<FormSchema[]>([
  {
    field: 'admin_dept_id',
    label: '管理部门',
    component: 'TreeSelect',
    componentProps: {
      data: myDeptList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: myUserListChange
    }
  },
  {
    field: 'admin_user_id',
    label: '管理用户',
    component: 'TreeSelect',
    componentProps: {
      data: myUserList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeAdminUser
    }
  },
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '所属用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'name',
    component: 'Input',
    label: '配方名'
  },
  {
    field: 'threshold',
    component: 'Input',
    componentProps: {
      placeholder: '例：1.2'
    },
    label: '默认阀值'
  },
  {
    field: 'totalWeight',
    component: 'Input',
    componentProps: {
      placeholder: '输入公斤数',
      onChange: onChangeWeight
    },
    label: '饲料重量'
  },
  {
    field: 'note',
    component: 'Input',
    label: '备注'
  }
])

const { register, methods, elFormRef } = useForm({
  schema: props.id ? schemaEdit : schemaAdd
})
const rules = reactive({
  name: [required],
  pasture_org_id: [required],
  totalWeight: [required],
  threshold: [required]
})

const d_id = ref(0) //主要用来给每个行添加一个序号，删除的时候好定位
const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'add_d':
      d_id.value++
      if (selectDataValue.value) {
        data.value.detailed.forEach((element) => {
          if (element.forage_id == selectDataValue.value[0]) {
            element.forage_name = selectDataValue.value[1]
          }
        })
      }
      data.value.detailed.push({
        d_id: d_id.value,
        forage_id: '',
        forage_name: '',
        weight: '',
        ratio: ''
      })
      break
    case 'del_d':
      let row_i = data.value.detailed.findIndex((item) => {
        return item.d_id == row.d_id
      })
      data.value.detailed.splice(row_i, 1)
      break
    default:
      console.log('未知类型')
  }
}

const d_columns1 = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'forage_id',
    label: '饲料名称',
    width: 150
  },
  {
    field: 'ratio',
    label: '比例%'
  },
  {
    field: 'weight',
    label: '重量（公斤）'
  },
  {
    field: 'action',
    width: 60,
    fixed: 'right',
    label: '操作'
  }
])

const d_columns2 = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'forage_id',
    label: '饲料名称',
    width: 150
  },
  {
    field: 'weight',
    label: '重量（公斤）'
  },
  {
    field: 'ratio',
    label: '比例%'
  },
  {
    field: 'action',
    width: 60,
    fixed: 'right',
    label: '操作'
  }
])

let selectDataValue = ref()

const clickFood = () => {
  if (selectDataValue.value) {
    data.value.detailed.forEach((element) => {
      if (element.forage_id == selectDataValue.value[0]) {
        element.forage_name = selectDataValue.value[1]
      }
    })
  }
}
const changeFood = (val) => {
  selectDataValue.value = val
}
const handleChange = async (val) => {
  let formData = await methods.getFormData()
  let value = val.ratio.replace(/[^\d.]/g, '') // 只能输入数字和.
  value = value.replace(/^\./g, '') //第一个字符不能是.
  value = value.replace(/\.{2,}/g, '.') // 不能连续输入.
  value = value.replace(/(\.\d+)\./g, '$1') // .后面不能再输入.
  value = value.replace(/^0+(\d)/, '$1') // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
  value = value.replace(/(\d{3})\d*/, '$1') // 最多保留3位整数
  value = value.replace(/(\.\d{2})\d*/, '$1') // 最多保留2位小数

  let aaa = Number(value)
  data.value.detailed.forEach((element) => {
    if (val.d_id != element.d_id) {
      aaa += Number(element.ratio)
      if (aaa > 100) {
        value = value.substr(0, val.ratio.length - 1)
        ElMessage({
          message: '饲料配比不能超过100%',
          type: 'warning'
        })
      }
    } else {
      if (val.ratio > 100) {
        ElMessage({
          message: '饲料配比不能超过100%',
          type: 'warning'
        })
        value = value.substr(0, val.ratio.length - 1)
      }
    }
    val.ratio = value
    if (formData?.totalWeight) {
      element.weight = formData?.totalWeight * element.ratio * 0.01
    }
  })
}
const weightChange = async () => {
  if (tabValue.value == '2') {
    data.value.totalWeight = data.value.detailed.reduce((prev, next) => {
      return prev + Number(next.weight)
    }, 0)
    await methods.setValues(data.value)
    data.value.detailed.forEach((element) => {
      element.ratio = ((element.weight * 100) / data.value.totalWeight).toFixed(2)
    })
  }
}

const init = () => {
  getForageFormulaSee()
}

watch(
  () => data.value,
  (val) => {
    if (!val) return
    methods.setValues(val)
  },
  {
    deep: true,
    immediate: true
  }
)

init()

defineExpose({
  elFormRef,
  getFormData: methods.getFormData,
  tableDatas: tableDatas
})
</script>

<template>
  <div>
    <Form :rules="rules" @register="register" :data="data" />
    <ContentWrap title="明细数据" v-if="data.pasture_org_id">
      <div class="mb-10px">
        <ElButton type="primary" @click="action('add_d')">添加饲料</ElButton>
      </div>
      <ElTabs type="border-card" v-model="tabValue" class="demo-tabs">
        <!-- @tab-change="tabChange(tabValue)" -->
        <ElTabPane
          v-for="(item, index) in belong_type"
          :key="index"
          :label="item.label"
          :name="item.value"
        >
          <Table
            v-if="tabValue == '1'"
            :columns="d_columns1"
            :data="data.detailed"
            :selection="false"
            :border="true"
          >
            <template #forage_id="{ row }">
              <FoodRefer
                v-model="row.forage_id"
                :getListApi="spForageList"
                :response="{ count: 'count', data: 'data' }"
                title="选择饲料（双击选择）"
                nameField="name"
                relNameField="name"
                valueField="id"
                :crudSchemas="[
                  { field: 'is_selected', label: '是否已选', search: { show: false }, width: 90 },
                  { field: 'name', label: '饲料名称', search: { show: true } }
                ]"
                :selected="data.detailed"
                :modelName="row.forage_name"
                @click="clickFood"
                @change="changeFood"
              />
            </template>
            <template #ratio="{ row }">
              <ElInput
                v-if="tabValue == '1'"
                v-model="row.ratio"
                type="tel"
                min="0"
                max="100"
                @input="handleChange(row)"
                placeholder="不大于100，例：50"
              />
            </template>
            <template #action="{ row }">
              <ElButton circle :icon="iconDel" @click="action('del_d', row)" title="删除行" />
            </template>
          </Table>
          <Table
            v-if="tabValue == '2'"
            :columns="d_columns2"
            :data="data.detailed"
            :selection="false"
            :border="true"
          >
            <template #forage_id="{ row }">
              <FoodRefer
                v-model="row.forage_id"
                :getListApi="spForageListApi"
                :response="{ count: 'count', data: 'data' }"
                title="选择饲料（双击选择）"
                nameField="name"
                relNameField="name"
                valueField="id"
                :crudSchemas="[
                  { field: 'is_selected', label: '是否已选', search: { show: false }, width: 90 },
                  { field: 'name', label: '饲料名称', search: { show: true } }
                ]"
                :selected="data.detailed"
                :modelName="row.forage_name"
                @click="clickFood"
                @change="changeFood"
              />
            </template>
            <template #weight="{ row }">
              <ElInput
                v-model="row.weight"
                type="number"
                maxlength="9"
                placeholder="公斤数"
                @input="weightChange"
              />
            </template>
            <template #ratio="{ row }">
              <ElInput
                v-if="tabValue == '1'"
                v-model="row.ratio"
                type="tel"
                min="0"
                max="100"
                @input="handleChange(row)"
                placeholder="不大于100，例：50"
              />
            </template>
            <template #action="{ row }">
              <ElButton circle :icon="iconDel" @click="action('del_d', row)" title="删除行" />
            </template>
          </Table>
        </ElTabPane>
      </ElTabs>
    </ContentWrap>
  </div>
</template>
